/*******************************************************************************
 * Copyright (c) 2014 Steffen Mikkelsen
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Contributors:
 *     Steffen Mikkelsen - initial API and implementation
 ******************************************************************************/
package com.subsecret.secureconnection.streamtools;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.junit.Test;

public class StreamToolsTest {
    
    @Test
    public void testShortConversion() throws Exception {
        testCaseShort(Short.MIN_VALUE);
        testCaseShort(Short.MAX_VALUE);
        testCaseShort((short) 0);
        testCaseShort((short) -2000);
        testCaseShort((short) 2000);
    }
    
    @Test
    public void testIntegerConversion() throws Exception {
        testCaseInteger(Integer.MIN_VALUE);
        testCaseInteger(Integer.MAX_VALUE);
        testCaseInteger(0);
        testCaseInteger(-2000);
        testCaseInteger(2000);
    }
    
    @Test
    public void testSendLargeByteArray() throws IOException {
        byte[] test = new byte[100000];
        for (int i = 0; i < test.length; i++) {
            test[i] = (byte) i;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamTools.sendByteArray(baos, test);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        byte[] receiveByteArray = StreamTools.receiveByteArray(bais);
        org.junit.Assert.assertArrayEquals(test, receiveByteArray);
    }
    
    @Test
    public void testSendSmallByteArray() throws IOException {
        byte[] test = new byte[1000];
        for (int i = 0; i < test.length; i++) {
            test[i] = (byte) i;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamTools.sendByteArray(baos, test);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        byte[] receiveByteArray = StreamTools.receiveByteArray(bais);
        org.junit.Assert.assertArrayEquals(test, receiveByteArray);
    }
    
    public void testCaseShort(short s) {
        short res = StreamTools.byteArrayToShort(StreamTools.shortToByteArray(s));
        org.junit.Assert.assertEquals(s, res);
    }
    
    public void testCaseInteger(int i) {
        int res = StreamTools.byteArrayToInt(StreamTools.intToByteArray(i));
        org.junit.Assert.assertEquals(i, res);
    }
    
}
